unit FView;

interface
uses
	Windows, OpenGl, FOpenGl, FBase, Math, FKeys, FCursor, FFPS, FLogs, SysUtils, FTerrain, FFrustum;

type
	TView = Record
		camx : Extended;
		camy : Extended;
		camz : Extended;

		tarx : Extended;
		tary : Extended;
		tarz : Extended;

		angle : Extended;
	end;

var
	View : TView;

const
	BorderOffset = 10;
	MoveFactor = 2;

procedure InitView();
procedure UpdateView();
procedure OnUpdateView();
procedure OnMouseMoveView(X : integer; Y : integer);

implementation

procedure CalculateView();
begin
	if View.tarx < TileSize * 10 then
		View.tarx := TileSize * 10;
	if View.tarx > TileSize * TerrainSize - TileSize * 10 then
		View.tarx := TileSize * TerrainSize - TileSize * 10;
	
	if View.tary < TileSize * 6 then
		View.tary := TileSize * 6;
	if View.tary > TileSize * TerrainSize - TileSize * 6 then
		View.tary := TileSize * TerrainSize - TileSize * 6;

	View.camx := View.tarx;
	View.camy := View.tary - View.camz * tan(View.angle);
end;

procedure UpdateView();
begin
	glViewport(0, 0, Window.X, Window.Y);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(80, Window.X / Window.Y, 1, 3000);
	gluLookAt(View.camx, View.camy, View.camz, View.tarx, View.tary, View.tarz, 0, 1, 0);    //1650
	ExtractFrustum();
end;

procedure InitView();
begin
	View.tarx := TileSize * 40;
	View.tary := TileSize * 40;
	View.camz := 700;

	View.tarz := 0;
	View.angle := 6.5;

	CalculateView();
	UpdateView();
end;

procedure OnMouseMoveView(X : integer; Y : integer);
begin
	if isWinKeyDown(VK_MBUTTON) then begin
		View.tarx := View.tarx - (X - Mouse.X)/2;
		View.tary := View.tary + (Y - Mouse.Y)/2;
		UpdateView();
	end;
	CalculateView();

	Mouse.X := X;
	Mouse.Y := Y;
end;

procedure OnUpdateView();
begin
	SetCursor(CU_NORMAL);

	if not isWinKeyDown(VK_MBUTTON) then begin
		if isKeyDown(FO_LEFT) or (Mouse.X < BorderOffset) then begin
			View.tarx := View.tarx - (MoveFactor * Count.Elapsed);
			if not isKeyDown(FO_LEFT) then
				SetCursor(CU_ARROW, true, false, false, false);
			CalculateView();
		end;

		if isKeyDown(FO_RIGHT) or (Mouse.X > Window.X - BorderOffset) then begin
			View.tarx := View.tarx + (MoveFactor * Count.Elapsed);
			if not isKeyDown(FO_RIGHT) then
				SetCursor(CU_ARROW, false, true, false, false);
			CalculateView();
		end;

		if isKeyDown(FO_UP) or (Mouse.Y < BorderOffset) then begin
			View.tary := View.tary + (MoveFactor * Count.Elapsed);
			if not isKeyDown(FO_UP) then
				SetCursor(CU_ARROW, false, false, true, false);
			CalculateView();
    end;

    if isKeyDown(FO_DOWN) or (Mouse.Y > Window.Y - BorderOffset) then begin
      View.tary := View.tary - (MoveFactor * Count.Elapsed);
      if not isKeyDown(FO_DOWN) then
        SetCursor(CU_ARROW, false, false, false, true);
      CalculateView();
		end;
  end;
end;

end.

